package today.rocky.elegantcoding.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import today.rocky.elegantcoding.component.LocalCache;
import today.rocky.elegantcoding.entity.User;
import today.rocky.elegantcoding.entity.UserExample;
import today.rocky.elegantcoding.mapper.UserMapper;
import today.rocky.elegantcoding.service.UserService;
import today.rocky.elegantcoding.util.RedisOpsUtil;

import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @vlog:
 * @description:
 * @author: Rocky
 * @createDate: 2020/6/6 18:17
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;

	@Autowired
	private LocalCache cache;

	@Autowired
	private RedisOpsUtil redisOpsUtil;
	/**
	 * zk分布式锁
	 *
	 */
//	@Autowired
//	private ZKLock zkLock;
//	private String lockPath = "/load_db";

	@Override
	public User getUserByIdUseCache(Integer id) {
		User user = null;
		user = cache.get("USER:" + id);
		//一级缓存
		if(user != null){
			return user;
		}
		//从二级缓存Redis里找
		user = redisOpsUtil.get("USER:" + id,User.class);
		if(user!=null){
			cache.setLocalCache("USER:" + id,user);
			return user;
		}
		//查询用户信息
		user = userMapper.selectByPrimaryKey(id);
		if (user == null) {
			//缓存到一级缓存
			cache.setLocalCache("USER:" + id, null);
			//商品信息缓存到reids当中，缓存被动更新
			redisOpsUtil.set("USER:" + id, "", 60, TimeUnit.SECONDS);
			return null;
		}
		//缓存到一级缓存
		cache.setLocalCache("USER:" + id, user);
		//商品信息缓存到reids当中，缓存被动更新
		redisOpsUtil.set("USER:" + id, user, 60, TimeUnit.SECONDS);
		/*if(zkLock.lock(lockPath + "_" + id)) {
			//查询详情信息
			user = userMapper.selectByPrimaryKey(id);
			if (user == null) {
				return null;
			}

			//缓存到一级缓存
			cache.setLocalCache("USER:" + id, user);
			//商品信息缓存到reids当中，缓存被动更新
			redisOpsUtil.set("USER:" + id, user, 3600, TimeUnit.SECONDS);
			zkLock.unlock(lockPath + "_" + id);
		}else{
			user = redisOpsUtil.get("USER:" + id,User.class);
			if(user != null){
				cache.setLocalCache("USER:" + id,user);
			}
		}*/
		return user;
	}
	@Override
	public User getUserByIdUseRedis(Integer id) {
		User user = null;
		//从Redis里找
		user = redisOpsUtil.get("USER:" + id,User.class);
		if(user!=null){
			return user;
		}
		//查询用户信息
		user = userMapper.selectByPrimaryKey(id);
		if (user == null) {
			redisOpsUtil.set("USER:" + id, "", 60, TimeUnit.SECONDS);
			return null;
		}
		redisOpsUtil.set("USER:" + id, user, 60, TimeUnit.SECONDS);
		return user;
	}

	@Override
	public User getUserByIdUseDB(Integer id) {
		return userMapper.selectByPrimaryKey(id);
	}


	@Override
	public int updateUser(User user) {
		UserExample example = new UserExample();
		example.createCriteria().andIdEqualTo(user.getId());
		return userMapper.updateByExampleSelective(user, example);
	}
}
